package com.moon.controller;

import cn.hutool.core.io.IoUtil;
import com.moon.pojo.OldUser;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class SpringBootBasicController {

    @RequestMapping("/list")
    public List<OldUser> list() {
        //1.加载并读取文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");
        ArrayList<String> lines = IoUtil.readLines(in, StandardCharsets.UTF_8, new ArrayList<>());
        //22、23行代码，我修改了user.txt内容不会即使生效，需要重启才能生效？？
        //2.解析数据，封装成对象 --> 集合
        List<OldUser> userList = lines.stream().map(line -> {
            String[] parts = line.split(",");
            Integer id = Integer.parseInt(parts[0]);
            String username = parts[1];
            String password = parts[2];
            String name = parts[3];
            Integer age = Integer.parseInt(parts[4]);
            LocalDateTime updateTime = LocalDateTime.parse(parts[5], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            return new OldUser(id, username, password, name, age, updateTime);
        }).collect(Collectors.toList());

        //3.响应数据
        //return JSONUtil.toJsonStr(userList, JSONConfig.create().setDateFormat("yyyy-MM-dd HH:mm:ss"));
        return userList;
    }


    @RequestMapping("/download")
    public void downloadFile(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition", "attachment; filename=4130642b-87ed-43d1-8606-46bf9d6ab49b.jpg");

        // 2. 读取文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("files/4130642b-87ed-43d1-8606-46bf9d6ab49b.jpg");

        // 3. 将文件内容写入响应流
        StreamUtils.copy(in, response.getOutputStream());


        // 4. 刷新输出流
        response.flushBuffer();
    }

    /**
     * 使用 FileInputStream 而不是 getResourceAsStream()；
     * 文件名要用 URLEncoder.encode() 进行编码，防止中文文件名导致 Content-Disposition 报错；
     * 设置 Content-Type 为 image/jpeg（你可以根据文件实际类型动态设置）；
     * 使用 try-with-resources 自动关闭流；
     * 如果文件找不到，返回 404 错误。
     * @param response
     * @throws IOException
     */
    @RequestMapping("/download3")
    public void downloadWithNormalFileStream(HttpServletResponse response) throws IOException {
        // 文件名（真实项目中建议作为参数传入）
        String fileName = "4130642b-87ed-43d1-8606-46bf9d6ab49b.jpg";

        // 构建完整文件路径
        String filePath = System.getProperty("user.dir") + File.separator + "files" + File.separator + fileName;

        // 设置响应类型
        response.setContentType("image/jpeg");

        // 防止文件名中有中文或特殊字符乱码，需进行编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");

        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        // 用 FileInputStream 读取文件
        try (InputStream in = new FileInputStream(filePath)) {
            StreamUtils.copy(in, response.getOutputStream());
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件未找到");
        }
    }


    //downloadFile方法的功能用responseEntiy来实现
    @RequestMapping("/download2")
    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
        // 1. 读取文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("user.txt");

        // 2. 准备响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);
        headers.setContentDispositionFormData("attachment", "user.txt");

        // 3. 构建 ResponseEntity
        assert in != null;
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(in.available())  // 可选：设置文件长度
                .body(new InputStreamResource(in));
    }

}